import os
from flask import Flask, jsonify, render_template,send_from_directory
import numpy as np
import webbrowser

app = Flask(__name__)

app.config['DOWNLOAD_FOLDER'] = 'Visualization'  # 替换为你的文件存储路径

def generate_data():
    L = 30  # 跨度 30米
    E = 3e10  # 弹性模量 30 GPa (混凝土典型值)
    I = 0.8  # 截面惯性矩 m^4
    P = 150e3  # 固定的集中荷载值
    q = 10e3  # 固定的均布荷载值

    x_points = np.linspace(0, L, 100)
    deflections_point = [calculate_deflection(L, E, I, 'point', P, x) for x in x_points]
    deflections_dist = [calculate_deflection(L, E, I, 'distributed', q, x) for x in x_points]

    return {
        "x": x_points.tolist(),
        "deflections_point": deflections_point,
        "deflections_dist": deflections_dist
    }

def calculate_deflection(L, E, I, load_type, load_value, x=None):
    if load_type == 'point':
        P = load_value
        if x is None:
            return (P * L**3) / (48 * E * I)
        else:
            return (P * x * (3 * L**2 - 4 * x**2)) / (48 * E * I) if x <= L/2 else \
                   (P * (L - x) * (3 * L**2 - 4 * (L - x)**2)) / (48 * E * I)
    
    elif load_type == 'distributed':
        q = load_value
        if x is None:
            return (5 * q * L**4) / (384 * E * I)
        else:
            return (q * x * (L**3 - 2 * L * x**2 + x**3)) / (24 * E * I)
    
    else:
        raise ValueError("无效荷载类型，请选择 'point' 或 'distributed'")

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/plot')
def plot():
    return render_template('plot.html')


@app.route('/product')
def product():
    return render_template('product.html')

@app.route('/team')
def team():
    return render_template('team.html')

@app.route('/get_data')
def get_data():
    data = generate_data()
    return jsonify(data)

@app.route('/download/<filename>')
def download_file(filename):
    try:
        # 检查文件是否存在
        file_path = os.path.join(app.config['DOWNLOAD_FOLDER'], filename)
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件 {filename} 不存在")
        
        # 发送文件
        return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename, as_attachment=True)
    except FileNotFoundError:
        abort(404)  # 如果文件不存在，返回 404 错误

if __name__ == '__main__':
    app.run(debug=True,port=8080)
    webbrowser.open("http://127.0.0.1:8080")

